jQuery.getScript('../../_utils/script/couch.js');

s3db = new Object;

s3db.userlogin = function(){// create HTML element to mediate user login and saves credentials in s3db.user
	//$('<div id="userlogin">URL: <input type=text> username: <input type=text> password: <input type=password></div>').appendTo(document.body);
	this.user.url='http://localhost:5984/';
	this.db={name:'s3db'};


}

s3db.checkuser = function(){//check that the user exist and define it otherwise
	if (!this.user){
	this.user={};
	this.userlogin();
	}
};

s3db.start=function(x){
	if (!x){var x=':-)'};
	console.log(x);
	this.checkuser();



	return true;
}

// S3QL
// It is probably not a good idea to parse S3QL
// client side but lets see how far can we go in
// using the fact that this would be a call comming
// from a HTML document hosted in the same domain
// as the Couch database. It would be fantastic
// if we could force the client to also do the parsing :D
s3db.s3ql = function(q){
	// SELECT takes precedence
	if (q.select){
		
		switch (q.select){
		case 'project':
			s3db.P=[];
			this.select=function(x){// define callback function first
				for(i in x){s3db.P[x[i]]={}} // creating blank projects
			}
			console.log('selecting projects');
			$.getJSON('/_all_dbs',this.select);//<-- use callback define above
			break;
		case 'doc': // this is not S3QL, it is a shortcut to probe Couch
			if (!q.where){q.where={};if (!q.where.project){q.where.project='s3db'}};
			// first atempt to use design documents
			$.getJSON('/'+q.where.project+'/_all_docs',function(x){s3db.docC=x;console.log(q)});// client side solution
			$.getJSON('/'+q.where.project+'/_design/s3ql/_view/all_docs',function(x){s3db.docS=x;console.log(q)});// server side solution
			$.getJSON('/'+q.where.project+'/_design/s3ql/_view/count_docs?group=true',function(x){s3db.docGroup=x;console.log(q)});// server side reduce

			break;
		default:
			return Error('did not understand what to select');
		}
	}
}




